package Demo42;

/**
 * 外观数列
 * https://leetcode.cn/problems/count-and-say/
 * 模拟实现题目要求
 */

class Solution {
    public String countAndSay(int n) {
        String ret = "1";
        for(int i = 1; i < n;i++) {
            int len = ret.length(),left = 0,right = 0;
            StringBuilder tmp = new StringBuilder();
            while(right < len) {
                while( right < len&& ret.charAt(left) == ret.charAt(right) ) right++;
                tmp.append(Integer.toString(right - left));
                tmp.append(ret.charAt(left));
                left = right;
            }
            ret = tmp.toString();
        }
        return ret;
    }

    public String countAndSay1(int n) {
        String ret = "1";
        for(int i = 2; i <= n;i++) {
            int left = 0,right = 0;
            char[] s = ret.toCharArray();
            int len = s.length;
            StringBuilder tmp = new StringBuilder();
            int index = 0;
            while(right < s.length) {
                if(s[left] != s[right]) {
                    tmp.append(String.valueOf(right - left));
                    tmp.append(s[left]);
                    left = right;
                }
                right++;
            }
            tmp.append((char) (String.valueOf((right - left))).toCharArray()[0]);
            tmp.append((char) (s[left]));
            ret = tmp.toString();
        }
        return ret;
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String ret = solution.countAndSay(2);
        System.out.println(ret);
    }
}